<script setup>
import List from '../components/List.vue';
import ClusterNamespaceSelector from '../components/ClusterNamespaceSelector.vue'
import { getCronJobListHandler as getListHandler, deleteCronJobHandler as deleteHandler ,updateCronJobHandler as updateHandler } from '../../api/cronjob';
import {reactive, computed, ref, toRefs} from 'vue'
import { ElMessage,ElMessageBox  } from 'element-plus'
import GenericOptions from '../components/GenericOptions.vue';
// import CodeMirror  from '../components/CodeMirror.vue'
import DialogYaml from '../components/DialogYaml.vue';
import { obj2Yaml } from '../../utils/utils';
import { useRouter } from 'vue-router';
const router = useRouter()
const data = reactive({
  items: [],
  clusterId: "",
  namespace: "",
  yamlContent: ""
})
// 定义一个查询Pod列表的函数
const getList = () => {
  getListHandler(data.clusterId, data.namespace).then(
    (res) => {
      data.items = res.data.data.items
      console.log("items:",data.items)
    }
  )
}
// 回调函数
const rollback = (clusterId, namespace)=> {
  data.clusterId = clusterId
  data.namespace = namespace
  getList()
}
const search = ref('')
const filterTableData = computed(() => {
  if (!data.items) return [] // 如果 items 不存在，返回空数组
  return data.items.filter(item => 
    !search.value ||
    item.metadata?.name?.toLowerCase().includes(search.value.toLowerCase())
  )
})
// 删除的方法
const deleteItem = (row, force) => {
  console.log("删除:", row)
  ElMessageBox.confirm(
    `你确定要删除命名空间: ${data.namespace} CronJob: ${row.metadata.name}吗？`,
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      deleteHandler(data.clusterId, data.namespace, row.metadata.name).then(
        (res) => {
          ElMessage({
              message: res.data.message,
              type: 'warning',
          })
          getList()
        }
      )
    })
    .catch(() => {
      return
    })

  
}
// 编辑的的方法
const editItem = (name) => {
  console.log("编辑资源:", data.clusterId,data.namespace,name)
  router.push({
    path: '/cronjob/edit',
    query: {
      clusterId: data.clusterId,
      namespace: data.namespace,
      name: name,
    }
  })
}

// 展示详情
const showDetail = ref(false)
const detail = (row) => {
  const item = JSON.parse(JSON.stringify(row))
  // 删除managedFields
  delete item.metadata.managedFields
  // 把apiVersion kind补上去
  const itemtemp = {
    "apiVersion": "batch/v1",
    "kind": "CronJob",
    "metadata": item.metadata,
    "spec": item.spec
  }
  // 把当前数据转成yaml
  const yamlData = obj2Yaml(itemtemp)
  data.yamlContent = yamlData
  showDetail.value = true
}
const updatePaused = async(row) => {
    console.log("当前的值:",row.spec.suspend)
    //如果true: 关闭暂停更新
    //如果false：打开暂停更新
    //更新节点的状态
    const postData = {
        clusterId: data.clusterId,
        namespace: data.namespace,
        item: row
      }
       await updateHandler(postData)
       .then((res) => {
           if (res.data.status == 200){
            ElMessage.success(res.data.message)
           }else {
            ElMessage.error(res.data.message)
            row.spec.suspend = !row.spec.suspend
          }
        }).catch(() => {
            err =>{
              row.spec.suspend = !row.spec.suspend
            }
        })
}
const {yamlContent,clusterId} = toRefs(data)
const handleChange = (value) => {
  console.log(value)
}
</script>

<template>
  <List title="CronJob列表">
    <template #header-options>
      <ClusterNamespaceSelector @namespaceChangedRollback="rollback">

      </ClusterNamespaceSelector>
      <el-input v-model="search" size="small" placeholder="搜索" style="width: 140px; margin-left: 10px; height: 32px;" />
    </template>
    <template #main>
      <el-table
      border 
      height="480" 
      :data="filterTableData" 
      style="width: 100%"
      :default-sort="{prop: 'metadata.creationTimestamp', order: 'descending'}"
      >
        <el-table-column fixed prop="" align="center" label="名称" width="320">
          <template #default="scope">
            <el-button link type="primary"  @click="detail(scope.row)">{{ scope.row.metadata.name }}</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="metadata.creationTimestamp" align="center" label="创建时间" width="240" sortable />
        <el-table-column prop="spec.schedule" align="center" label="调度策略" width="240" />
        <el-table-column  prop="" align="center" label="暂停调度" width="320">
          <template #default="scope">
            <el-switch v-model="scope.row.spec.suspend" 
            @change="updatePaused(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="spec.concurrencyPolicy" sortable align="center" label="并发策略" width="240" />

        <el-table-column prop="status.lastScheduleTime" align="center" label="上一次调度时间" width="240" sortable />
        <el-table-column prop="status.lastSuccessfulTime" align="center" label="上一次执行成功时间" width="240" sortable />

        <el-table-column prop="metadata.namespace" align="center" label="命名空间" width="240" />
        <el-table-column fixed="right" align="center" label="操作" width="320" >
          <template #default="scope">
            <GenericOptions
            v-on:delete-rollback="getList"
            :name="scope.row.metadata.name"
            :cluster-id="clusterId"
            :disabled ="scope.row.metadata.deletionTimestamp" 
            resource-type="CronJob"
            :namespace="scope.row.metadata.namespace"
            :show-schedule-options="true"
            :item="scope.row"
            >
            </GenericOptions>
           </template>
        </el-table-column>
      </el-table>
    </template>
  </List>
  <DialogYaml
  :cluster-id="data.clusterId"
  :namespace="data.namespace"
  :yaml-content="yamlContent"
  :show-dialog="showDetail"
  @close-dialog-handler="(val)=>{showDetail = val}"
  >

  </DialogYaml>
  <!-- <el-dialog
  v-model="showDetail" 
  width="70%">
  <template #header="{ titleId, titleClass }">
    <div class="my-header">
      <div :id="titleId" :class="titleClass" style="margin: 10px auto 0 auto;">
        <el-button type="primary" title="资源所在的集群" >
          <i class="iconfont icon-kubernetes" style="font-size: 20px;" />
          <span style="font-size: 20px;margin-left: 10px;">{{ data.clusterId }}</span>
        </el-button>
        <el-button type="primary" title="资源所在的命名空间" >
          <i class="iconfont icon-Namespace" style="font-size: 20px;" />
          <span style="font-size: 20px;margin-left: 10px;">{{ data.namespace }}</span>
        </el-button>
      </div>
    </div>
  </template>
    <CodeMirror
    v-model="yamlContent"
    ></CodeMirror>
  </el-dialog> -->
</template>

<style scoped>
.my-header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}
</style>
